<?php

namespace App\Http\Controllers\admin;

use App\Http\Controllers\Controller;
use App\Models\MaterialTemplate;
use App\Services\MaterialTemplateService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class MaterialTemplateController extends Controller
{
    protected $MaterialTemplateService;
    public function __construct(MaterialTemplateService $MaterialTemplateService)
    {
        $this->MaterialTemplateService = $MaterialTemplateService;
    }

    public function index(Request $Request) {
        if(!$Request->type){
            return response()->json(['code' => '404', 'msg' => '类型错误']);
        }
        if(!$Request->material_contract_id){
            return response()->json(['code' => '404', 'msg' => '请选择合同']);
        }
        $data = MaterialTemplate::with('project')->with('contract')->where('type',$Request->type)->where('material_contract_id',$Request->material_contract_id)->first();
        if($data){
            $data->is_approved = false;
            $data->content = json_decode($data->content);
            if($data->contract){
                if($data->contract->application){
                    $data->is_approved = $data->contract->application->status == 'approved' ? true : false;
                }
            }
        }

        return response()->json(['code' => '200', 'msg' => '操作成功','data'=>$data]);
    }

    /**
     * 存储一个新数据。
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $Request)
    {
        if(!$Request->material_contract_id){
            return response()->json(['code' => '404', 'msg' => '请选择要操作的记录']);
        }
        $POSTONLY = MaterialTemplate::POSTONLY;
        $input = $Request->only($POSTONLY);
        $input['project_id'] = $Request->project_id;
        $input['user_id'] = Auth::user()->id;
        $data = $this->MaterialTemplateService->insert($input);
        return response()->json(['code' => '200', 'msg' => '操作成功','data'=>$data]);
    }


    public function update(Request $Request)
    {
        if(!$Request->material_contract_id){
            return response()->json(['code' => '404', 'msg' => '请选择要操作的记录']);
        }

        $POSTONLY = MaterialTemplate::POSTONLY;
        $input = $Request->only($POSTONLY);
        $input['project_id'] = $Request->project_id;
        $input['user_id'] = Auth::user()->id;
        $data = $this->MaterialTemplateService->update($input);
        return response()->json(['code' => '200', 'msg' => '操作成功','data'=>$data]);
    }

    public function delete(Request $Request)
    {
        if(!$Request->id){
            return response()->json(['code' => '404', 'msg' => '请选择要操作的记录']);
        }
        $data = MaterialTemplate::find($Request->id);
        $data->delete();
        return response()->json(['code' => '200', 'msg' => '操作成功']);
    }
}
